﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Data;
using System.IO;
using Excel;

public class LocaliztionTool : EditorWindow
{
    static string excelPath = Application.dataPath + "/Language/Language.xlsx";
    static string languagePath = Application.dataPath+"/Language/";

    [MenuItem("Tools/LocaliztionTool")]
    public static void CreateLocaliztionTxt()
    {
        List<LanguageData> languageDataList = new List<LanguageData>();
        int columnNum = 0;      // 列数
        int rowNum = 0;         // 行数
        DataRowCollection collect = ReadExcel(excelPath, ref columnNum, ref rowNum);
        Debug.Log(string.Format("列数：{0}  行数：{1}", columnNum, rowNum));
        for (int i = 1; i < columnNum; i++)
        {
            LanguageData ld = new LanguageData();
            ld.language = collect[0][i].ToString();  
            string path = string.Format("{0}{1}.txt", languagePath, ld.language);
            string txtStr = string.Empty;
            for(int j = 1;j<rowNum;j++)
            {
                ld.keyValueDic.Add(collect[j][0].ToString(), collect[j][i].ToString());
                txtStr += string.Format("{0} = {1}\n", collect[j][0].ToString(), collect[j][i].ToString());
            }
            CreateLanguageTxt(path, txtStr);
            Debug.Log("path:" + path);
            Debug.Log("txtStr:" + txtStr);
        }

        AssetDatabase.Refresh();
        AssetDatabase.SaveAssets();
    }

    static void CreateLanguageTxt(string path,string txtStr)
    {
        StreamWriter sw;
        FileInfo fi = new FileInfo(path);
        sw = fi.CreateText();
        sw.WriteLine(txtStr);
        sw.Close();
        sw.Dispose();
    }

    /// <summary>
    /// 读取excel文件内容
    /// </summary>
    /// <param name="filePath">文件路径</param>
    /// <param name="columnNum">行数</param>
    /// <param name="rowNum">列数</param>
    /// <returns></returns>
    static DataRowCollection ReadExcel(string filePath, ref int columnNum, ref int rowNum)
    {
        FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
        IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
        DataSet result = excelReader.AsDataSet();
        //Tables[0] 下标0表示excel文件中第一张表的数据
        columnNum = result.Tables[0].Columns.Count;
        rowNum = result.Tables[0].Rows.Count;
        return result.Tables[0].Rows;
    }
}

public class LanguageData
{
    public string language;
    public Dictionary<string, string> keyValueDic = new Dictionary<string, string>();
}



